package com.hsfw.pmbasicdata.service.impl;

import com.hsfw.dbmodule.dao.ArmyDataDao;
import com.hsfw.dbmodule.dao.BasicDataDao;
import com.hsfw.dbmodule.dao.DeployDataDao;
import com.hsfw.pmbasicdata.service.BasicDataService;
import com.hsfw.pmbasicdata.utils.SingleVolBasicData;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BasicDataServiceImpl implements BasicDataService {
    @Autowired
    BasicDataDao basicDataDao;
    @Autowired
    ArmyDataDao armyDataDao;
    @Autowired
    DeployDataDao deployDataDao;
    @Autowired
    SingleVolBasicData singleVolBasicData;
    /**
     * 基础数据
     * */
    String base = "base";
    /**
     * 部队编制
     * */
    String army = "army";
    /**
     * 部署数据类型
     * */
    String deploy = "deploy";
    /**
     * 表名
     * */
    String dataaircraft = "dataaircraft";
    String dataship = "dataship";
    String datasubmarine = "datasubmarine";
    String datafacility = "datafacility";
    String datasatellite = "datasatellite";
    String dataweapon = "dataweapon";
    String sensor = "sensor";
    String comm = "comm";
    String mount = "mount";
    String loadout = "loadout";
    String signature = "signature";
    String weaponsignature = "weaponsignature";
    String code = "code";
    String propulsion = "propulsion";
    String fuel = "fuel";
    String aircraftfacilities = "aircraftfacilities";
    String magazine = "magazine";
    String warhead = "warhead";
    String target = "target";
    String dockingfacilities = "dockingfacilities";
    String director = "director";
    String wra = "wra";
    String weapondamageability = "weapondamageability";
    String mobilecategory = "mobilecategory";
    /**
     * 组装前台数据需要的key
     * */
    String prop = "prop";
    String label = "label";
    String tableHead = "tableHead";
    String fieldname = "fieldname";
    String value = "value";
    String type = "type";
    /**
     * 序号map
     * */
    List<HashMap<String, Object>> overallTableHeadData;
    /**
     * type和表名的对应关系map
     * */
    HashMap<String, String> tableMap;
    /**
     * 实体表名和图片表的对应关系map
     * */
    HashMap<String, String> imageTableMap;
    /**
     * 地面兵力与设施的子分类，中英文对应的map
     * */
    HashMap<String, String> mobileCategoryMap;
    BasicDataServiceImpl(){
        tableMap = new HashMap();
        tableMap.put("aircraft", dataaircraft);
        tableMap.put("ship", dataship);
        tableMap.put("submarine", datasubmarine);
        tableMap.put("facility", datafacility);
        tableMap.put("satellite", datasatellite);
        tableMap.put("weapon", dataweapon);

        overallTableHeadData = new ArrayList<>();
        HashMap<String, Object> middleMap1 = new HashMap<>();
        middleMap1.put(type, "index");
        middleMap1.put(label, "序号");
        overallTableHeadData.add(middleMap1);
        HashMap<String, Object> middleMap2 = new HashMap<>();
        middleMap2.put(prop, fieldname);
        middleMap2.put(label, "属性");
        overallTableHeadData.add(middleMap2);
        HashMap<String, Object> middleMap3 = new HashMap<>();
        middleMap3.put(prop, value);
        middleMap3.put(label, "值");
        overallTableHeadData.add(middleMap3);

        imageTableMap = new HashMap<>();
        imageTableMap.put(dataaircraft, "aircraftimage");
        imageTableMap.put(dataship, "shipimage");
        imageTableMap.put(datasubmarine, "submarineimage");
        imageTableMap.put(datafacility, "facilityimage");
        imageTableMap.put(datasatellite, "satelliteimage");
        imageTableMap.put(dataweapon, "weaponimage");

        mobileCategoryMap = new HashMap<>();
        mobileCategoryMap.put("None", "未分类");
        mobileCategoryMap.put("Inf", "步兵团");
        mobileCategoryMap.put("Armored", "装甲车");
        mobileCategoryMap.put("Arty", "火炮");
        mobileCategoryMap.put("SSM", "炮兵部队地地导弹");
        mobileCategoryMap.put("AAA", "防空高炮");
        mobileCategoryMap.put("SAM", "地空导弹");
        mobileCategoryMap.put("Engineer", "工程");
        mobileCategoryMap.put("Supply", "补给车");
        mobileCategoryMap.put("Radar", "监控车");
        mobileCategoryMap.put("Recon", "侦察车");
        mobileCategoryMap.put("Mech", "机械化步兵");
    }


    @Override
    public List<HashMap<String, Object>> getTreeMenuByNodeID(String nodeId, String ifNodeAll,String treeType) {
        if ("YES".equals(ifNodeAll)) {
            return singleVolBasicData.gettreeMenuAll(treeType);
        } else if ("INIT".equals(ifNodeAll)) {
            return getAllNode(nodeId, "YES",treeType);
        } else if ("REFRESH".equals(ifNodeAll)) {
            return singleVolBasicData.refreshTreeMenuAll(treeType);
        } else {
            return getAllNode(nodeId, ifNodeAll,treeType);
        }
    }

    @Override
    public List<HashMap<String, Object>> getTableNameList(String tableName) {
        return basicDataDao.getTableHeader(tableName);
    }

    @Override
    public HashMap<String,Object> getTableInfoListByParentId(String treeType, String tableName,
                                                             String parentId, int startPage,int pagNum) {
        HashMap res=new HashMap();
        if (tableName==null){
            tableName=dataaircraft;
        }
        String nodes = "nodes";
        String num = "num";
        // 20200426 邓康欣 取节点及节点下所有节点的guid集合，组装成以逗号分割的字符串
        List<String> allParentIdList = getNodeAllChildren(treeType, "'"+parentId+"'");
        allParentIdList.add(parentId);
        String allParentIdStr = convertListToString(allParentIdList);
        if (base.equalsIgnoreCase(treeType)) {
            /*
             * 基础数据获取，dataaircraft——飞机，dataship——水面舰艇，datasubmarine——潜艇，datafacility——地面兵力与设施,
             * datasatellite-卫星，dataweapon——武器，共六大实体
             */
            if (dataaircraft.equalsIgnoreCase(tableName)) {
                res.put(nodes, basicDataDao.getAircraftTable(allParentIdStr, (startPage - 1) * pagNum, pagNum));
                res.put(num, basicDataDao.getTableNum(allParentIdStr, tableName));
            } else if (dataship.equalsIgnoreCase(tableName)) {
                res.put(nodes, basicDataDao.getShipTable(allParentIdStr, (startPage - 1) * pagNum, pagNum));
                res.put(num, basicDataDao.getTableNum(allParentIdStr, tableName));
            } else if (datasubmarine.equalsIgnoreCase(tableName)) {
                res.put(nodes, basicDataDao.getSubmarineTable(allParentIdStr, (startPage - 1) * pagNum, pagNum));
                res.put(num, basicDataDao.getTableNum(allParentIdStr, tableName));
            } else if (datafacility.equalsIgnoreCase(tableName)) {
                res.put(nodes, basicDataDao.getFacilityTable(allParentIdStr, (startPage - 1) * pagNum, pagNum));
                res.put(num, basicDataDao.getTableNum(allParentIdStr, tableName));
            } else if (datasatellite.equalsIgnoreCase(tableName)) {
                res.put(nodes, basicDataDao.getSatelliteTable(allParentIdStr, (startPage - 1) * pagNum, pagNum));
                res.put(num, basicDataDao.getTableNum(allParentIdStr, tableName));
            } else if (dataweapon.equalsIgnoreCase(tableName)) {
                // 2020/4/22 邓康欣 武器的国家可以多选，需要特殊处理.（数据格式为：多个国家的编号以英文“,”做分隔）
                List<HashMap<String, Object>> weaponData = basicDataDao.getWeaponTable(allParentIdStr, (startPage - 1) * pagNum, pagNum);
                for (HashMap<String, Object> eachWeaponData : weaponData) {
                    String countryList = eachWeaponData.get("operatorcountry").toString();
                    String[] countryNameList = basicDataDao.getWeaponCountryNames(countryList);
                    // 2020/4/22 邓康欣 把多个国家名称拼接成一个以逗号分割的字符串
                    eachWeaponData.put("operatorcountry", StringUtils.join(countryNameList, ","));
                }
                res.put(nodes, weaponData);
                res.put(num, basicDataDao.getTableNum(allParentIdStr, tableName));
            }
        }else if (army.equalsIgnoreCase(treeType)) {
            //  2020/4/22 邓康欣 部队编制数据获取
            res.put(nodes, armyDataDao.getArmyDataByNodeId(allParentIdStr,(startPage-1)*pagNum, pagNum));
            res.put(num, armyDataDao.getTableNum(allParentIdStr));
        } else if (deploy.equalsIgnoreCase(treeType)) {
            List<HashMap<String, Object>> dirList = deployDataDao.getDirDataByNodeId(parentId);
            List<HashMap<String, Object>> hostRecordData;
            if (dirList.isEmpty()) {
                // 叶子节点情况，对应db_hostedrecords表
                hostRecordData = deployDataDao.getFileDataByNodeId(parentId);
                res.put(num, 1);
            } else {
                // 目录情况，对应db_deployfile表
                hostRecordData = deployDataDao.getFileDataByParentId(allParentIdStr,(startPage - 1) * pagNum, pagNum);
                res.put(num, deployDataDao.getFileCount(allParentIdStr));
            }
            // 每条数据，根据挂载实体的GUID和Type，取军标图片
            for (HashMap<String, Object> eachMap : hostRecordData) {
                String tableType = eachMap.get("membertype").toString().toLowerCase();
                eachMap.put("iconimage", deployDataDao.getIconImage(tableMap.get(tableType), eachMap.get("member_dbguid").toString()));
            }
            res.put(nodes, hostRecordData);
        }

        return res;
    }

    /**
     * @date 20200426
     * @author 邓康欣
     * 根据nodeId取该节点下所有的子节点、孙子节点、孙孙子节点...的guid集合
     */
    private List<String> getNodeAllChildren(String treeType, String nodeId) {
        List<String> allNodeIdList = new ArrayList<>();
        if (base.equalsIgnoreCase(treeType)) {
            allNodeIdList = basicDataDao.getChildIdListByParentIdList(nodeId);
        } else if (army.equalsIgnoreCase(treeType)) {
            allNodeIdList = armyDataDao.getChildIdListByParentIdList(nodeId);
        } else if (deploy.equalsIgnoreCase(treeType)) {
            allNodeIdList = deployDataDao.getChildDirIdListByParentIdList(nodeId);
        }

        if (!allNodeIdList.isEmpty()) {
            String allNodeIdStr = convertListToString(allNodeIdList);
            allNodeIdList.addAll(getNodeAllChildren(treeType, allNodeIdStr));
        }
        return allNodeIdList;
    }

    private List<HashMap<String, Object>> getAllNode(String nodeId, String ifNodeAll,String treeType) {
        List<HashMap<String, Object>> res = new ArrayList<>();
        // 2020/4/23 邓康欣 根据不同的树类型取树数据，”base“-基础数据，”army“-部队编制，”deploy“-部署数据
        if (base.equalsIgnoreCase(treeType)) {
            res = basicDataDao.getBaseTreeMenuByNodeID(nodeId);
        } else if (army.equalsIgnoreCase(treeType)) {
            res = armyDataDao.getArmyTreeMenuByNodeID(nodeId);
        } else if (deploy.equalsIgnoreCase(treeType)) {
            res = deployDataDao.getDeployTreeOfDFMenuByNodeID(nodeId);
            res.addAll(deployDataDao.getDeployTreeOfHRMenuByNodeID(nodeId));
        }
        if ("YES".equals(ifNodeAll)) {
            for (HashMap map : res) {
                map.put("children", getAllNode(map.get("guid").toString(), "YES",treeType));
            }
        }
        return res;
    }

    /**
     * @date 20200426
     * @author 邓康欣
     * 将List<String>集合 转化为'1','2','3','4','5'
     */
    public static String convertListToString(List<String> strlist){
        StringBuilder sb = new StringBuilder();
        if(!CollectionUtils.isEmpty(strlist)){
            for (int i=0;i<strlist.size();i++) {
                if(i==0){
                    sb.append("'").append(strlist.get(i)).append("'");
                }else{
                    sb.append(",").append("'").append(strlist.get(i)).append("'");
                }
            }
        }
        return sb.toString();
    }

    /**
     * @date 20200429
     * @author 邓康欣
     * 根据表名和guid取实体的总体数据信息及挂载组件的中间信息
     */
    @Override
    public List getEntityInfoById(String guid, String tableName) {
        List<HashMap<String, Object>> returnData = new ArrayList<>();
        // 总体数据
        HashMap<String, Object> overallDataMap = new HashMap<>();
        overallDataMap.put("tableName", "总体数据");
        // 表头信息，总体数据只有两列
        overallDataMap.put(tableHead, overallTableHeadData);
        // 表数据
        List<HashMap<String, String>> tableData = new ArrayList<>();
        List<HashMap<String, String>> overallData = new ArrayList<>();
        if (dataaircraft.equalsIgnoreCase(tableName)) {
            overallData = basicDataDao.getAircraftOverallData(guid);
        } else if (dataship.equalsIgnoreCase(tableName)) {
            overallData = basicDataDao.getShipOverallData(guid);
        } else if (datasubmarine.equalsIgnoreCase(tableName)) {
            overallData = basicDataDao.getSubmarineOverallData(guid);
        } else if (datafacility.equalsIgnoreCase(tableName)) {
            overallData = basicDataDao.getFacilityOverallData(guid);
            // 地面兵力与设施的列子分类需要特殊处理，
            for (HashMap<String, String> eachMap : overallData) {
                if (eachMap.containsKey(mobilecategory)) {
                    String mobilecategoryValue = eachMap.get(mobilecategory);
                    if (mobileCategoryMap.containsKey(mobilecategoryValue)) {
                        eachMap.put(mobilecategory, mobileCategoryMap.get(mobilecategoryValue));
                    } else {
                        eachMap.put(mobilecategory, "未分类");
                    }
                }
            }
        } else if (datasatellite.equalsIgnoreCase(tableName)) {
            overallData = basicDataDao.getSatelliteOverallData(guid);
        } else if (dataweapon.equalsIgnoreCase(tableName)) {
            overallData = basicDataDao.getWeaponOverallData(guid);
        }
        List<HashMap<String, String>> overalllField = basicDataDao.getOverallField(tableName);
        // 按照格式组装数据，例如：fieldname——名称，value——“jk飞机”
        for (HashMap<String, String> eachFieldMap : overalllField) {
            String fieldnameValue = eachFieldMap.get(fieldname).toLowerCase();
            String translate = eachFieldMap.get("translate");
            HashMap<String, String> mMap = new HashMap<>();
            mMap.put(fieldname, translate);
            for (HashMap<String, String> eachMap : overallData) {
                if (eachMap.containsKey(fieldnameValue)) {
                    mMap.put(value, eachMap.get(fieldnameValue));
                } else {
                    // 如果没有，存一个空字符
                    mMap.put(value, "");
                }
            }
            tableData.add(mMap);
        }

        overallDataMap.put("tableData", dealSpecialValue(tableData));
        // 获取实体图片base64
        overallDataMap.put("entityImage", basicDataDao.getEntityImage(imageTableMap.get(tableName.toLowerCase()), guid));
        returnData.add(overallDataMap);
        //取实体的所有组件信息（表名，翻译），再根据该信息去循环取组件的table信息
        List<HashMap<String, String>> allComponentData = basicDataDao.getAllComponentData(tableName);
        for (HashMap<String, String> eachMap : allComponentData) {
            HashMap<String, Object> eachComponentMap = getComponentTableData(guid,
                                                                            eachMap.get("tablename"),
                                                                            eachMap.get("translate"));
            returnData.add(eachComponentMap);
        }

        return returnData;
    }

    /**
     * @date 20200429
     * @author 邓康欣
     * 根据表名、guid和翻译取组件的中间信息
     */
    private HashMap<String, Object> getComponentTableData(String guid, String tableName, String translate) {
        HashMap<String, Object> componentDataMap = new HashMap<>();
        componentDataMap.put("tableName", translate+"数据");
        List<HashMap<String, String>> tableData = new ArrayList<>();
        // 根据表名调用不同的dao接口取数据
        // sensor和director都是取的sensor表，director组件只有武器有
        if (tableName.toLowerCase().indexOf(sensor) != -1 || tableName.toLowerCase().indexOf(director) != -1) {
            // 表头信息
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(sensor));
            // 表数据
            tableData = basicDataDao.getSensorComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(comm) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(comm));
            tableData = basicDataDao.getCommComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(mount) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(mount));
            tableData = basicDataDao.getMountComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(loadout) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(loadout));
            tableData = basicDataDao.getLoadoutComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(signature) != -1) {
            // 武器的信号特征没有top这一列，需要特殊处理
            if (tableName.toLowerCase().indexOf(weaponsignature) != -1) {
                componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(weaponsignature));
                tableData = basicDataDao.getWeaponsignatureComponentData(tableName, guid);
            } else {
                componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(signature));
                tableData = basicDataDao.getSignatureComponentData(tableName, guid);
            }
        } else if (tableName.toLowerCase().indexOf(code) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(code));
            // 不同实体挂载的属性组件链接到不同的枚举表,这里取枚举表名称
            String enumTableName = basicDataDao.getEnumCodeTableName(tableName);
            tableData = basicDataDao.getCodeComponentData(tableName, enumTableName, guid);
        } else if (tableName.toLowerCase().indexOf(propulsion) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(propulsion));
            tableData = basicDataDao.getPropulsionComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(fuel) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(fuel));
            tableData = basicDataDao.getFuelComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(aircraftfacilities) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(aircraftfacilities));
            tableData = basicDataDao.getAircraftFacilitiesComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(magazine) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(magazine));
            tableData = basicDataDao.getMagazineComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(target) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(target));
            tableData = basicDataDao.getTargetComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(warhead) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(warhead));
            tableData = basicDataDao.getWarheadComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(dockingfacilities) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(dockingfacilities));
            tableData = basicDataDao.getDockingFacilitiesComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(wra) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(wra));
            tableData = basicDataDao.getWraComponentData(tableName, guid);
        } else if (tableName.toLowerCase().indexOf(weapondamageability) != -1) {
            componentDataMap.put(tableHead, SingleVolBasicData.componentTableHead.get(weapondamageability));
            tableData = basicDataDao.getWeapondamageabilityComponentData(tableName, guid);
        }

        componentDataMap.put("tableData", dealSpecialValue(tableData));
        return componentDataMap;
    }
    /**
     * @date 20200430
     * @author 邓康欣
     * 处理数据，比如：false装换成否
     */
    private List<HashMap<String, String>> dealSpecialValue(List<HashMap<String, String>> data) {
        for (HashMap<String, String> eachMap : data) {
            for(Map.Entry<String, String> entry: eachMap.entrySet()) {
                String eachValue = String.valueOf(entry.getValue());
                if ("false".equalsIgnoreCase(eachValue)) {
                    eachMap.put(entry.getKey(), "否");
                } else if ("true".equalsIgnoreCase(eachValue)) {
                    eachMap.put(entry.getKey(), "是");
                }
            }
        }
        return data;
    }
}
